<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2>传递json给服务器</h2>
    <button class="btn1">获取</button>
    <button class="btn2">新增</button>
    <button class="btn3">修改</button>
    <button class="btn4">删除</button>
    <script>
      function myAxios(option) {
        // console.log(option);
        const { url, method = "get", data } = option;
        // console.log(data);
        return new Promise((resolve, reject) => {
          // 处理异步任务
          // 原生 ajax
          const xhr = new XMLHttpRequest();
          xhr.open(method, url);
          // 设置请求头数据类型
          xhr.setRequestHeader("content-type", "application/json");
          xhr.addEventListener("load", () => {
            // 将成功的结果交给 resolve
            console.log(xhr.response);
            resolve(xhr.response);
          });
          xhr.send(JSON.stringify(data));
        });
      }

      document.querySelector(".btn1").addEventListener("click", () => {
        myAxios({
          method: "get",
          url: "http://ajax-api.itheima.net/api/books",
        }).then((res) => {
          const data = JSON.parse(res);
          console.log(data);
        });
      });

      // 新增
      document.querySelector(".btn2").addEventListener("click", () => {
        myAxios({
          method: "post",
          url: "http://ajax-api.itheima.net/api/books",
          data: {
            bookname: "黑马程序员",
            author: "小马",
            publisher: "北京出版社",
          },
        }).then((res) => {
          console.log(res);
        });
      });

      // 修改
      document.querySelector(".btn3").addEventListener("click", () => {
        myAxios({
          method: "put",
          url: "http://ajax-api.itheima.net/api/books/5",
          data: {
            bookname: "三体",
            author: "大刘",
            publisher: "北京出版社",
          },
        }).then((res) => {
          console.log(res);
        });
      });

      // 删除
      document.querySelector(".btn4").addEventListener("click", () => {
        myAxios({
          method: "delete",
          url: "http://ajax-api.itheima.net/api/books/5",
        }).then((res) => {
          console.log(res);
        });
      });
    </script>
  </body>
</html>
